<template>
  <el-container class="layout-container">
    <SystemNotificationBar />
    
    <el-header class="layout-header">
      <div class="header-content">
        <div class="logo">{{systemCfg.title }}</div>
        <div class="menu-wrapper">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleMenuSelect"
          >
            <el-menu-item 
              v-for="item in visibleMenuItems" 
              :key="item.index" 
              :index="item.index"
              class="menu-item"
            >
              <svg v-if="item.icon && item.icon.startsWith('i-')" class="icon" aria-hidden="true">
                <use :xlink:href="'#' + item.icon"></use>
              </svg>
              <el-icon v-else>
                <component :is="icons[item.icon]" />
              </el-icon>
              <span>{{ item.title }}</span>
            </el-menu-item>
          </el-menu>
        </div>
        <div class="toolbar">
          <div class="user-info" v-if="user">
            <el-dropdown @command="handleUserCommand">
              <div class="user-dropdown">
                <el-avatar :size="36" :src="user.avatar">{{ user.name?.charAt(0) }}</el-avatar>
                <span class="user-name">{{ user.name }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="documentation">
                    <el-icon><Document /></el-icon>
                    项目文档
                  </el-dropdown-item>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人资料
                  </el-dropdown-item>
                  <el-dropdown-item command="logout" divided>
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </el-header>
    
    <el-main class="layout-main" :class="props.fullPage ? 'layout-main_full' : ''">
      <div class="content-wrapper">
        <slot></slot>
      </div>
    </el-main>

    <!-- 个人资料弹窗 -->
    <el-dialog
      v-model="profileDialogVisible"
      title="个人资料"
      width="500px"
      :before-close="handleProfileDialogClose"
    >
      <UserProfileForm
        v-model="profileForm"
        :is-create="false"
        @success="handleProfileSuccess"
        @error="handleProfileError"
      />
    </el-dialog>

    <!-- 项目文档抽屉 -->
    <ProjectDocumentationDrawer 
      v-model:visible="documentationVisible" 
    />
  </el-container>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { House, User, SwitchButton, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import UserProfileForm from './UserProfileForm.vue'
import ProjectDocumentationDrawer from './ProjectDocumentationDrawer.vue'
import SystemNotificationBar from './SystemNotificationBar.vue'
import type { User as UserType } from '@/api/modules/user'
import { logout } from '@/api/modules/user'
import systemCfg from '@/assets/systemCfg'
import { setUserPermissions, isPageVisible } from '@/utils/permission'
import { getUserPermissions } from '@/api/modules/permission'
import websocket from '@/utils/websocket'
import {useSystemNotificationStore} from "@/stores/systemNotification";

// 获取系统通知 store 实例
const systemNotificationStore = useSystemNotificationStore()
const props = withDefaults(defineProps<{
  fullPage?: boolean
}>(), {
  fullPage: false
})

// 图标映射
const icons: Record<string, any> = {
  House,
  User,
  SwitchButton,
  Document
}

const router = useRouter()
const route = useRoute()

// 用户信息
const user = ref<UserType | null>(null)

// 个人资料弹窗可见性
const profileDialogVisible = ref(false)

// 项目文档抽屉可见性
const documentationVisible = ref(false)

// 个人资料表单数据
const profileForm = ref<Partial<UserType> | null>(null)

// 是否有未读通知
const hasUnreadNotifications = computed(() => systemNotificationStore.systemUnreadCount > 0)

// 从localStorage获取用户信息
const loadUserInfo = async () => {
  try {
    const userStr = localStorage.getItem('user')
    if (userStr) {
      user.value = JSON.parse(userStr)
      // 初始化个人资料表单数据
      profileForm.value = { ...user.value }
      // 确保密码字段为空，避免显示之前输入的密码
      if (profileForm.value) {
        profileForm.value.password = ''
      }
      
      // 加载用户权限
      await loadUserPermissions(user.value.user_id)
    }
  } catch (e) {
    console.error('解析用户信息失败', e)
    user.value = null
  }
}

// 加载用户权限
const loadUserPermissions = async (userId: number) => {
  try {
    const res = await getUserPermissions(userId)
    // 设置用户权限到工具模块
    setUserPermissions(res.data.permissions)
  } catch (error) {
    console.error('加载用户权限失败:', error)
  }
}

// 显示项目文档
const showDocumentation = () => {
  documentationVisible.value = true
}

// 监听路由变化，重新加载用户信息（以防在其他地方更新了用户信息）
watch(
  () => route.fullPath,
  () => {
    loadUserInfo()
  }, {deep: true, immediate: true}
)

// 从路由配置中提取菜单项，并根据权限过滤
const visibleMenuItems = computed(() => {
  const items = router.options.routes
    .filter(route => {
      return route.meta && route.meta.menu
    })
    .map(route => ({
      index: route.meta!.menu!.index,
      title: route.meta!.menu!.title,
      icon: route.meta!.menu!.icon
    }))
  // 根据pageShow字段过滤菜单项
  return items.filter(item => {
    // 根据路由路径找到对应的权限分类键名
    const permissionKey = item.index.split('/')[1] || ''
    // 根据权限控制菜单显示
    return isPageVisible(permissionKey)
  })
})

// 获取当前激活的菜单项
const activeMenu = computed(() => {
  const currentRoute = router.currentRoute.value

  // 检查是否有父级路由，并且父级路由有菜单配置
  const parentPath = currentRoute.path.split('/').slice(0, 2).join('/')
  const parentRoute = router.options.routes.find(r => r.path === parentPath)
  if (parentRoute && parentRoute.meta?.menu) {
    return parentRoute.meta.menu.index
  }

  return currentRoute.meta?.menu?.index || ''
})

const handleMenuSelect = (index: string) => {
  router.push(index)
}

// 处理用户下拉菜单命令
const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'documentation':
      // 显示项目文档
      documentationVisible.value = true
      break
    case 'profile':
      // 显示个人资料弹窗
      profileDialogVisible.value = true
      break
    case 'logout':
      try {
        // 调用后端注销接口
        await logout()
      } catch (error) {
        console.error('注销接口调用失败:', error)
      } finally {
        // 退出登录
        localStorage.removeItem('user')
        websocket.close(true);
        // 清空系统通知数据 销毁store实例
        systemNotificationStore.clearNotifications()
        systemNotificationStore.$dispose()
        ElMessage.success('已退出登录')
        router.push('/')
      }
      break
  }
}

// 处理个人资料弹窗关闭
const handleProfileDialogClose = () => {
  // 清除表单中的密码信息
  if (profileForm.value) {
    profileForm.value.password = ''
  }
  profileDialogVisible.value = false
}

// 处理个人资料更新成功
const handleProfileSuccess = (updatedUser: UserType) => {
  // 更新localStorage中的用户信息
  if (user.value) {
    Object.assign(user.value, updatedUser)
    localStorage.setItem('user', JSON.stringify(user.value))
    // 同步更新profileForm中的数据
    if (profileForm.value) {
      Object.assign(profileForm.value, updatedUser)
      // 确保密码字段为空
      profileForm.value.password = ''
    }
  }

  // 关闭弹窗
  profileDialogVisible.value = false
}

// 处理个人资料更新失败
const handleProfileError = (error: any) => {
  console.error('更新个人资料失败:', error)
}
</script>

<style scoped>
.icon {
  width: 26px;
  height: 26px;
  vertical-align: middle;
  margin-right: 5px;
  fill: currentColor;
  overflow: hidden;
}

.layout-container {
  height: 100vh;
  flex-direction: column;
  overflow: hidden;
}

.layout-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  padding: 0;
  flex-shrink: 0;
  height: 50px;
}

.header-content {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 0 20px;
}

.logo {
  color: white;
  font-size: 20px;
  font-weight: bold;
  margin-right: 40px;
  white-space: nowrap;
  flex-shrink: 0;
}

.menu-wrapper {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  margin: 0 20px; /* 左右都留出20px边距，实现对称效果 */
  min-width: 0;
}

.el-menu.el-menu--horizontal {
  border-bottom: none;
  background: transparent;
  display: flex;
  min-width: fit-content;
}

:deep(.el-menu--horizontal > .el-menu-item) {
  color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  white-space: nowrap;
}

:deep(.el-menu--horizontal > .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.1) !important;
  color: #ffffff !important;
}

:deep(.el-menu--horizontal > .el-menu-item.is-active) {
  color: #ffffff !important;
  background: rgba(255, 255, 255, 0.15) !important;
}

:deep(.el-menu--horizontal > .el-menu-item .el-icon) {
  margin-right: 5px;
  width: 1em;
  height: 1em;
  vertical-align: middle;
}

:deep(.el-menu--horizontal .el-sub-menu__title) {
  height: 60px;
  line-height: 60px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-shrink: 0;
}

.doc-button {
  background: rgba(255, 255, 255, 0.15) !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
  color: white !important;
}

.doc-button:hover {
  background: rgba(255, 255, 255, 0.25) !important;
}

.user-info {
  flex-shrink: 0;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: white;
}

.user-name {
  margin-left: 10px;
  font-weight: 500;
  white-space: nowrap;
}

.layout-main {
  flex: 1;
  overflow: hidden;
  background: linear-gradient(135deg, #cbdefb 0%, #d1e0f8 100%);
  padding: 20px;
  height: calc(100vh - 50px);
}
.layout-main_full {
  padding: 0;
}

.layout-main_full .content-wrapper > :slotted(*) {
  border-radius: 0;
}

.content-wrapper {
  height: 100%;
  overflow: auto;
}

.content-wrapper > :slotted(*) {
  margin: 0 auto;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}
</style>